<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-row>
      <el-col :span="22">
        <el-form :model="param" :inline="true" label-width="70px">
          <el-form-item label="箱号" style="width:260px" >
              <MultipleBoxNumbersDialog v-model="param.containerNo" clearable/>
          </el-form-item>
          <el-form-item label="业务编号" style="width:260px">
            <el-input v-model="param.businessNo" clearable  placeholder="输入业务编号"/>
          </el-form-item>
          <el-form-item label="箱型" style="width:260px">
            <el-select v-model="param.boxType" clearable style="width:100%" placeholder="选择箱型">
              <el-option v-for="item in param.boxTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="箱况" style="width:260px">
            <el-select v-model="param.boxCondition" clearable style="width:100%" placeholder="选择箱况">
              <el-option v-for="item in param.boxCaseOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="提箱单号" style="width:260px">
            <el-input v-model="param.packingNo" clearable placeholder="请输入提箱单号"></el-input>
          </el-form-item>
          <el-form-item label="提箱日期" style="width:260px">
            <el-date-picker v-model="param.packingDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item label="箱东公司" style="width:260px">
            <el-input v-model="param.companyName" clearable placeholder="输入箱东公司名字"></el-input>
          </el-form-item>
          <el-form-item label="堆场名称" style="width:260px">
            <el-input v-model="param.yardName" clearable placeholder="输入业堆场名字"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="2">
          <el-row>
            <el-col :span="24"><el-button @click="handleReSet" :icon="Refresh">重置</el-button></el-col>
            <el-col :span="24" class="marginTop15"><el-button @click="getTableData" :icon="Search" type="primary" >查询</el-button></el-col>
          </el-row>
      </el-col>
    </el-row>
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <el-row class="floatRight">
        <!-- <el-button type="primary" size="small" @click="" plain>导出</el-button> -->
        <!-- <el-button :icon="Delete" type="primary" size="small" @click="handleDelete" plain>删除</el-button> -->
        <el-col :span="4"><el-button type="primary" size="small" @click="batchApply" plain>还箱申请</el-button></el-col>
    </el-row>
    <Table ref="tableRef" v-bind="table" style="width: 100%;" @pageChange="onTablePageChange" @activDelete="activDelete"
      @showInfo="showInfo" @jumpTo="jumpTo" @deleteBoxDetail="deleteBoxDetail" @activEdit="activEdit" @downloadBoxPhoto="downloadBoxPhoto" @hxView="hxView" @hxApply="hxApply"
       :disableHeaderCheckbox="disableHeaderCheckbox" >
    </Table>

    <!-- 提箱记录详情 -->
    <el-drawer v-model="param.dialogVisibleInfo" title="" :with-header="false">
      <span class="_before" v-if="typeDrawer==1">提箱记录详情</span>
      <span class="_before" v-else-if="typeDrawer==2">提箱记录编辑</span>
      <el-form :model="boxInfo" :rules="fromRules" label-width="100px" style="margin-top: 20px;">
        <el-form-item label="提箱单号：">{{ boxInfo.packingNo }}</el-form-item>
        <el-form-item label="堆场名称：">{{ boxInfo.yardName }}</el-form-item>
        <el-form-item label="箱型：">{{ boxTypeFilter(boxInfo.boxType) }}</el-form-item>
        <el-form-item label="箱况：">{{ boxConditionFilter(boxInfo.boxCondition) }}</el-form-item>
        <el-form-item label="车牌号：" v-if="typeDrawer==1">{{ boxInfo.plateNumber || '无' }}</el-form-item>
        <el-form-item label="车牌号：" v-if="typeDrawer==2"><el-input v-model.trim="boxInfo.plateNumber" placeholder="请输入车牌号" clearable></el-input></el-form-item>
        <el-form-item label="箱号：">{{ boxInfo.containerNo }}</el-form-item>
        <el-form-item label="提箱日期：">{{ formatDate(boxInfo.packingDate, 2) }}</el-form-item>
        <el-form-item label="客户邮箱：" prop="customerEmail"><el-input v-model.trim="boxInfo.customerEmail" type="email" placeholder="请输入邮箱" clearable></el-input></el-form-item>
        <el-form-item label="提箱附件：">
          <showFile v-if="typeDrawer==1" :detailFileList="boxInfo.detailFileList"></showFile>  
          <ImgUpload ref="addBoxFileRef" v-else-if="typeDrawer==2"  :urlList="boxInfo.detailFileList" :displayType="2" :fileSize="3" :showNumber="4" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
        </el-form-item>
      </el-form>
      <template #footer v-if="typeDrawer==2">
        <div class="dialog-footer" style="display: flex; justify-content: center;">
            <el-button type="primary" @click="detaiClick">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- warning-->
    <el-dialog v-model="param.dialogVisible" title="系统提示" width="500">
      <span>确认删除该用户？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
          <el-button @click="param.dialogVisible = false">是的</el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="hxApplyDialog" :with-header="false" size="40%">
        <span class="_before">还箱申请</span>
        <el-row class="marginTop20">
            <el-col :span="24">类型：
                <el-radio-group v-model="returnBoxTypeValue" v-if="showType =='apply' || showType =='batch'">
                    <el-radio :value="10">箱属</el-radio>
                    <el-radio :value="15">还箱令</el-radio>
                    <!-- <el-radio :value="5">还箱单</el-radio> -->
                </el-radio-group>
                <span v-else-if="showType =='view'">{{{5:'还箱单',10:'箱属',15:'还箱令',null:'无数据'}[txjlInfo.returnBoxType]}}</span>
            </el-col>
        </el-row>
        <div v-if="showType =='batch'">
            箱号：
            <template v-for="(item,index) in txjlSelectionInfo" :key="index">
                {{item.containerNo}} <template v-if="index < (txjlSelectionInfo.length -1)">、</template>
            </template>
        </div>
        <el-row v-else class="marginTop20" >
            <el-col :span="8">箱号：{{txjlInfo.containerNo}}</el-col>
            <el-col :span="16" class="text-ellipsis">还箱地：
                <template v-if="txjlInfo.returnCity">
                    <el-tooltip effect="dark" :content="splitSrray(txjlInfo.returnCity)" placement="top">{{splitSrray(txjlInfo.returnCity)}}</el-tooltip>
                </template>
                <template v-else>--</template>
            </el-col>
        </el-row>
        <el-form :model="txjlInfo"  :rules="fromRules">
          <el-form-item prop="customerEmail" style="width: 100%;"  class="marginTop20">
            <el-row align="middle"  style="width:80%">
              <el-col :span="18">
                客户邮箱：<el-input v-model.trim="customerEmail" type="email" placeholder="请输入邮箱" clearable style="width:80%"></el-input> 
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        
        <template v-if="showType =='apply'">
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 10">
                <el-col :span="3">提箱照片：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef5" :limit="10" :urlList="JSON.parse(txjlInfo.detailFileList || '[]')" :type="'jpg/png/jpeg/pdf/zip'" :displayType="3" :drag="true" :showNumber="6"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" align="center" v-if="returnBoxTypeValue == 15">
                <el-col :span="5" class="_asterisk">预计还箱日期：</el-col>
                <el-col :span="10"><el-date-picker v-model="planReturnDate" type="date" :disabled-date="disabledDate" placeholder="还箱日期" style="width: 100%;"/></el-col>
            </el-row>
            <el-row class="marginTop20 _asterisk" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">到站运单：</el-col>
                <el-col :span="24" class="marginTop5" v-if="showType =='apply'">
                    <ImgUpload ref="packingRef6" :limit="10" :type="'jpg/png/jpeg/pdf/zip'" :displayType="3" :fileSize="5" :drag="true" :showNumber="6"></ImgUpload>
                </el-col>
                <el-col :span="24" class="marginTop5" v-else-if="showType =='view'">
                  <ImgUpload ref="packingRef6" :urlList="JSON.parse(txjlInfo.arrivalWaybill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">转关单：</el-col>
                <el-col :span="24" class="marginTop5" v-if="showType =='apply'">
                    <ImgUpload ref="packingRef7" :limit="10" :type="'jpg/png/jpeg/pdf/zip'" :displayType="3" :fileSize="5" :drag="true" :showNumber="6"></ImgUpload>
                </el-col>
                <el-col :span="24" class="marginTop5" v-else-if="showType =='view'">
                <ImgUpload ref="packingRef7" :urlList="JSON.parse(txjlInfo.turnCustomBill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
        </template>
        <template v-else-if="showType =='view'">
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 10">
                <el-col :span="3">提箱照片：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef5" :urlList="JSON.parse(txjlInfo.detailFileList || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" align="center" v-if="returnBoxTypeValue == 15">
                <el-col :span="5" class="_asterisk">预计还箱日期：</el-col>
                <el-col :span="10">{{formatDate(txjlInfo.planReturnDate,2)}}</el-col>
            </el-row>
            <el-row class="marginTop20 _asterisk" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">到站运单：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef6" :urlList="JSON.parse(txjlInfo.arrivalWaybill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">转关单：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef7" :urlList="JSON.parse(txjlInfo.turnCustomBill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
        </template>

        <el-row class="marginTop50" v-if="showType == 'apply' || showType =='batch'">
            <el-col :span="23" class="text-right">
                <el-button type="primary" @click="submitApplication">确认</el-button>
            </el-col>
        </el-row>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import { formatDate } from '@/utils'
import czTages from '@/components/chengzhiTags'
import { getDetailTable, deletePackingDetail,details ,returnApply,agentStatusCount,batchReturnApply} from '@/api/orderManage/packingDetail'
import { computed, onMounted, onActivated, reactive, ref,nextTick } from 'vue';
import ImgUpload from '@/components/upload/uploadFiles-Images'
import basicTools from '@/tools/index'
import { Plus, Delete, Edit, Message, Search, Download, Upload, Refresh, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus';
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import showFile from '@/components/upload/showFile.vue'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
import { useRoute, useRouter } from 'vue-router'
const fromRules = {
  customerEmail: [
    // { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
}

const param = reactive({
  value1: [],
  boxInfo: { code: '123456789', type: "40HQ", info: "无" },
  pageNum: 0,
  pageSize: 10,
  dialogTableVisible: false,
  drawer: false,
  dialogEditVisible: false,
  dialogVisible: false,
  dialogPathVisible: false,
  businessNo:'',
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '5', label: '全新', },
    { value: '10', label: '次新', },
    { value: '15', label: '适货', },
    // { value: '20', label: '混提(次新或者适货)', },
  ],
});
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'containerNo', colWidth: '120', title: '箱号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'boxType', colWidth: '80', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '80', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' }, isCheck: true },
    { key: 'packingDate', colWidth: '100', title: '提箱日期', type: 'date', isCheck: true },
    { key: 'businessNo', colWidth: '100', title: '业务编号', type: 'text', isCheck: true },
    { key:'carryCityName', colWidth: '80', title: '提箱城市', type: 'text', isCheck: true },
    { key:'returnCity', colWidth: '100', title: '还箱城市', type: 'moreCity', isCheck: true },
    { key: 'yardName',colWidth: '180', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'companyName', colWidth: '200', title: '集装箱公司', type: 'text', isCheck: true },
    { key: 'returnBoxType', colWidth: '90', title: '还箱类型', filter:{5:'还箱单',10:'箱属',15:'还箱令'},type: 'filter', isCheck: true },
    { key: 'boxEastOperatorUserName', colWidth: '90', title: '联系人', type: 'text', isCheck: true },
    { key: 'orderNo', colWidth: '190', title: '订单号', type: '<a>',command: 'jumpTo',parameter:'orderNo', isCheck: true },
    { key: 'packingNo', colWidth: '190', title: '提箱单号', type: '<a>',command: 'jumpTo',parameter:'packingNo', isCheck: true },
    {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          name: '删除',  
          command: 'deleteBoxDetail',
          // isShow: (row: any) => {
          //   return row.packingStatus == 15; //提箱单状态: 提箱中才有记录  5-已发放 10-已下载 15-提箱中 20-已完成 25-作废 30-已过期
          // },
        }, 
        {
          command: 'activEdit',
          name: '编辑',     
          // isShow: (row: any) => {
          //    return row.packingStatus < 20;
          // },
        },
        {
          command: 'hxApply',
          name: '还箱申请',     
          isShow: (row: any) => {
             return row.returnStatus < 12;
          },
        },
        {
          command: 'downloadBoxPhoto',
          name: '下载箱照'
        },
        {
          command: 'hxView',
          name: '查看申请',
          isShow: (row: any) => {
             return row.returnStatus  >= 12
          },
        }
      ]
    }
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});
const orderTypeval = ref("")
const route = useRoute();
onActivated(() => {
  if(route.query.refNo){
    param.containerNo=route.query.refNo
  }
  nextTick(() => {
      if(route.name=='JKreleaseInfoHD6'){
        orderTypeval.value = "10"
      }else{
        orderTypeval.value = "5"
      }
    getTableData()
    })

})

const getTableData = () => {
  const { container, containerList } = formatContainerNo(param.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    packingNo: param.packingNo?.trim(),
    orderType: orderTypeval.value,
    boxType: param.boxType,
    boxCondition: param.boxCondition,
    yardName: param.yardName?.trim(),
    companyName: param.companyName?.trim(),
    businessNo:param.businessNo,
    returnStatus: returnStatus.value
  }
  if (param.packingDate) {
    data.beginPackingDate = param.packingDate[0]
    data.endPackingDate = param.packingDate[1]
  }
  getAgentStatusCount(data)
  getDetailTable(data).then((res: any) => {
    table.data = res.data.list;
    table.config.total = res.data.total;
  })
}
// 重置
function handleReSet() {
  param.containerNo = ''
  param.packingNo = ''
  param.boxType = ''
  param.boxCondition = ''
  param.packingDate=[]
  param.companyName=''
  param.yardName=''
  param.businessNo=''
  getTableData()
}
const typeList =ref([
    { id: 0, name: '全部',num:0 },
    { id: 10, name: '未还',num:0 },
    { id: 12, name: '待还',num:0 },
    { id: 15, name: '还箱中',num:0 },
    { id: 20, name: '已还箱',num:0 },
])
// 查询各箱源状态的数量
const getAgentStatusCount = async(data:any) => { 
  await agentStatusCount(data).then((res: any) => {
    if(res.code == '00000'){
      typeList.value.forEach(item => { 
        item.num = 0
        res.data.forEach(item1 => { 
          if(item.id == 0){ //全部
            item.num += item1.totalQty
          }else if(item.id == 10 && item1.status == 10){ //未还
              item.num += item1.totalQty
          }else if(item.id == 12 && item1.status == 12){ //已申请
              item.num += item1.totalQty
          }else if(item.id == 15 && item1.status == 15){ //还箱中
              item.num += item1.totalQty
          }else if(item.id == 20 && item1.status == 20){ //已还箱
              item.num += item1.totalQty
          }
        })
      })
    }
  })
}
const returnStatus = ref(null) // 还箱状态 10-未还 12-已申请 15-还箱中 20-已还箱
function handleTypeChange(val: any) {
  // console.log(val)
  // param.statusType = val
  // param.containerClassify = val
  returnStatus.value = val
  getTableData()
  // deselectAll()
}

//编辑
const addBoxFileRef = ref()
const detaiClick = () =>{
  let data={
      id:boxInfo.value.id,
      plateNumber:boxInfo.value.plateNumber,
      customerEmail:boxInfo.value.customerEmail,
      detailFileList:JSON.stringify(addBoxFileRef.value.fileList),
  }
  details(data).then((res: any) => {
    if (res.code == "00000") {
      param.dialogVisibleInfo = false;
      getTableData()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//删除
const activDelete = (row: any) => {
  param.dialogVisible = true;
};

const deleteBoxDetail =  (row: any) => {
  ElMessageBox.confirm('删除之后无法恢复，请认真核对', '系统提示', 
  { 
    confirmButtonText: '确认', 
    cancelButtonText: '取消', 
    type: 'warning' }).then(async() => {
      await deletePackingDetail(row.id).then(() => {
        ElMessage.success('删除成功')
          getTableData()
        })
      }).catch(() => {
        ElMessage.error('删除失败，请刷新页面重试')
      });
 
}



//详情
const boxInfo = ref({})
const typeDrawer=ref(1) //1详情 2编辑
//详情
const showInfo = (row: any) => {
  typeDrawer.value=1
  boxInfo.value = row
  param.dialogVisibleInfo = true;
};
const router = useRouter();
const jumpTo = (row: any,type:any = '') =>{
  if(type == "packingNo"){ //跳转到提箱单页面
    router.push({
      path: '/tiXiangManageHD/tiXiangManageHD',
      // query: {
      //   boxId: row.releaseRentId,
      //   boxType: row.boxType,
      //   boxCondition: row.boxCondition,
      //   returnCityId: row.returnCityId
      // }
    });
  }else if(type == "orderNo"){ //跳转到订单页面
    router.push({
      path: '/orderManageHD/rentOrder',
      // query: {
      //   boxId: row.releaseRentId,
      //   boxType: row.boxType,
      //   boxCondition: row.boxCondition,
      //   returnCityId: row.returnCityId
      // }
    });
  }
}
//编辑
const activEdit = (row: any) => {
   typeDrawer.value=2
   let info=JSON.parse(JSON.stringify(row))
   boxInfo.value = info
   if(typeDrawer.value==2){
     boxInfo.value.detailFileList=JSON.parse(info.detailFileList)
    }
  param.dialogVisibleInfo = true;
};
//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//过滤
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}



const hxApplyDialog = ref(false)
const txjlInfo = ref({})
const returnBoxTypeValue = ref(10)
const planReturnDate = ref(new Date())
const showType = ref('apply')
const packingRef5 = ref()
const packingRef6 = ref()
const packingRef7 = ref()
// 查看还箱申请
const hxView = (row:any) => {
  showType.value = 'view'
  nextTick(() => {
        packingRef5.value?.clearFiles()
        packingRef6.value?.clearFiles()
        packingRef7.value?.clearFiles()

        txjlInfo.value = row  
        returnBoxTypeValue.value = txjlInfo.value.returnBoxType || 10
        hxApplyDialog.value = true
    })

}
// 下载箱照
const downloadBoxPhoto = (row:any) => {
  basicTools.batchDownloadFile(row.detailFileList,row.containerNo)
}
// 批量还箱申请
const tableRef = ref({ multipleSelection: []})
const txjlSelectionInfo = ref([])
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const batchApply = () => {
    showType.value = 'batch'
    returnBoxTypeValue.value = 10
    txjlSelectionInfo.value = tableRef.value.multipleSelection
    if(txjlSelectionInfo.value.length < 1) return ElMessage.warning('请选择需要申请还箱的集装箱')
    nextTick(() => {
        packingRef5.value?.clearFiles()
        packingRef6.value?.clearFiles()
        packingRef7.value?.clearFiles()

        returnBoxTypeValue.value = txjlInfo.value.returnBoxType || 10
        hxApplyDialog.value = true
    })
}
// 还箱申请
const hxApply = (row:any) => {
    showType.value = 'apply'
    returnBoxTypeValue.value = 10
    planReturnDate.value = new Date()
    nextTick(() => {
        packingRef5.value?.clearFiles()
        packingRef6.value?.clearFiles()
        packingRef7.value?.clearFiles()

        txjlInfo.value = row  
        returnBoxTypeValue.value = txjlInfo.value.returnBoxType || 10
        hxApplyDialog.value = true
    })
}
const  customerEmail = ref() // 客户邮箱
const submitApplication = async() => {
    if(showType.value == 'batch'){
        let txRecordarr = []
        txjlSelectionInfo.value.forEach(item => {
            let record = {id:item.id, returnBoxType: returnBoxTypeValue.value, customerEmail:customerEmail.value}
            txRecordarr.push(record)
        });
        await batchReturnApply(txRecordarr).then(res => {
            if(res.code == "00000"){
              getTableData()
                hxApplyDialog.value = false
                ElMessage.success("批量还箱申请发送成功")
            }else{
                ElMessage.warning(res.msg)
            }
        })
    }else{
        let data = {
            returnBoxType: returnBoxTypeValue.value,
            customerEmail:customerEmail.value
        }
        if(returnBoxTypeValue.value == 10){ //箱属
            data.detailFileList = JSON.stringify(packingRef5.value.fileList)
        }else if(returnBoxTypeValue.value == 15){ //还箱令
            data.planReturnDate = planReturnDate.value.toISOString(),
            data.arrivalWaybill = JSON.stringify(packingRef6.value.fileList)
            data.turnCustomBill = JSON.stringify(packingRef7.value.fileList)
        }
        await returnApply(txjlInfo.value.id,data).then(res => {
            if(res.code == "00000"){
                getTableData()
                hxApplyDialog.value = false
                ElMessage.success("还箱申请发送成功")
            }else{
                ElMessage.warning(res.msg)
            }
        }) 
    }

}


const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};
// 多个城市拼接
const splitSrray = (row:any) => {
  let newRow = []
  try{
    newRow = JSON.parse(row)
  }catch(e){
    newRow = []
  }
  let newRowStr = ''
  const newRowLength = newRow.length
  newRow.forEach((item,index) => { 
    if(index < newRowLength - 1){
      newRowStr += item.returnCityName + "、"
    }else{
      newRowStr += item.returnCityName
    } 
  })
  return newRowStr || '--'
}
</script>

<style scoped lang="scss">
.el-form-diy {
  padding: 10px;
  div {
    width: 100%;
  }
}
</style>
